// http://api.douban.com/v2/movie/subject/1764796?apikey=0df993c66c0c636e29ecbb5344252a4a
const rp = require('request-promise-native')
const mongoose = require('mongoose')

const fetchMovie = async (item) => {
  const url = `http://api.douban.com/v2/movie/subject/${item.doubanId}?apikey=0df993c66c0c636e29ecbb5344252a4a`
  let res = await rp(url)
  return res
}
(async () => {
  let Movie = mongoose.model('Movie')
  let Category = mongoose.model('Category')

  const movies = await Movie.find({
    $or: [
      { summary: { $exists: false }},
      { year: { $exists: false }},
      { summary: null },
      { summary: '' },
      { tags: [] },
      { category: [] },
    ]
  })
  movies.forEach(async movie => {
    let movieData = await fetchMovie(movie)
    movieData = JSON.parse(movieData)
    movie.tags = movieData.tags || []
    movie.summary = movieData.summary || ''
    movie.title = movieData.alt_title || movieData.title
    movie.rawTitle = movieData.title || ''
    movie.movieTypes = movieData.genres || []
    movie.year = movieData.year || 2500
    for (let i = 0; i < movie.movieTypes.length; i++) {
      let movieType = movie.movieTypes[i]
      let cate = await Category.findOne({ name: movieType })
      if (!cate) {
        cate = new Category({
          name: movieType,
          movies: [movie._id]
        })
      } else {
        if (cate.movies.indexOf(movie._id) === -1) {
          cate.movies.push(movie._id)
        }
      }
      await cate.save()
      if (!movie.category) {
        movie.category = [cate._id]
      } else {
        if (movie.category.indexOf(cate._id) === -1) {
          movie.category.push(cate._id)
        }
      }
    }
    let dates = movieData.pubdates || []
    let pubdates = []

    dates.forEach(item => {
      let date = /^(.*?)\(/.exec(item)[1]
      let country = /\((.*?)\)/.exec(item)[1]
      pubdates.push({
        date: new Date(date),
        country
      })
    })
    movie.pubdate = pubdates
    await movie.save()
  })
})()
